<template>
  <div class="system-log">
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 登录日志标签页 -->
      <el-tab-pane label="登录日志" name="login">
        <div class="search-bar">
          <el-form :inline="true" :model="loginSearchForm" class="demo-form-inline">
            <el-form-item label="用户名">
              <el-input v-model="loginSearchForm.username" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item label="IP地址">
              <el-input v-model="loginSearchForm.ip_address" placeholder="请输入IP地址" clearable />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="loginSearchForm.status" placeholder="请选择状态" clearable>
                <el-option label="成功" value="success" />
                <el-option label="失败" value="failed" />
              </el-select>
            </el-form-item>
            <el-form-item label="登录时间">
              <el-date-picker
                v-model="loginSearchForm.date_range"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchLoginLogs">查询</el-button>
              <el-button @click="resetLoginSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 登录日志表格 -->
        <el-table :data="loginLogs" style="width: 100%" v-loading="loginLoading">
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="ip_address" label="IP地址" />
          <el-table-column prop="login_address" label="登录地点" />
          <el-table-column prop="browser" label="浏览器" />
          <el-table-column prop="os" label="操作系统" />
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                {{ row.status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_time" label="登录时间" />
        </el-table>

        <!-- 登录日志分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="loginCurrentPage"
            v-model:page-size="loginPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="loginTotal"
            @size-change="handleLoginSizeChange"
            @current-change="handleLoginCurrentChange"
          />
        </div>
      </el-tab-pane>

      <!-- 操作日志标签页 -->
      <el-tab-pane label="操作日志" name="operation">
        <div class="search-bar">
          <el-form :inline="true" :model="operationSearchForm" class="demo-form-inline">
            <el-form-item label="用户名">
              <el-input v-model="operationSearchForm.username" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item label="请求方法">
              <el-select v-model="operationSearchForm.request_method" placeholder="请选择请求方法" clearable>
                <el-option label="GET" value="GET" />
                <el-option label="POST" value="POST" />
                <el-option label="PUT" value="PUT" />
                <el-option label="DELETE" value="DELETE" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态码">
              <el-input v-model="operationSearchForm.status" placeholder="请输入状态码" clearable />
            </el-form-item>
            <el-form-item label="操作时间">
              <el-date-picker
                v-model="operationSearchForm.date_range"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchOperationLogs">查询</el-button>
              <el-button @click="resetOperationSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 操作日志表格 -->
        <el-table :data="operationLogs" style="width: 100%" v-loading="operationLoading">
          <el-table-column prop="username_id" label="用户名" />
          <el-table-column prop="ip_address" label="IP地址" />
          <el-table-column prop="request_method" label="请求方法">
            <template #default="{ row }">
              <el-tag :type="getMethodTagType(row.request_method)">
                {{ row.request_method }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="request_url" label="请求地址" show-overflow-tooltip />
          <el-table-column prop="status" label="状态码">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="response_time" label="响应时间" />
          <el-table-column prop="action_time" label="操作时间" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button link type="primary" @click="showDetail(row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 操作日志分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="operationCurrentPage"
            v-model:page-size="operationPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="operationTotal"
            @size-change="handleOperationSizeChange"
            @current-change="handleOperationCurrentChange"
          />
        </div>

        <!-- 操作日志详情对话框 -->
        <el-dialog
          v-model="detailDialogVisible"
          title="操作日志详情"
          width="60%"
        >
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">{{ currentLog.username_id }}</el-descriptions-item>
            <el-descriptions-item label="IP地址">{{ currentLog.ip_address }}</el-descriptions-item>
            <el-descriptions-item label="请求方法">{{ currentLog.request_method }}</el-descriptions-item>
            <el-descriptions-item label="请求地址">{{ currentLog.request_url }}</el-descriptions-item>
            <el-descriptions-item label="状态码">{{ currentLog.status }}</el-descriptions-item>
            <el-descriptions-item label="响应时间">{{ currentLog.response_time }}</el-descriptions-item>
            <el-descriptions-item label="操作时间">{{ currentLog.action_time }}</el-descriptions-item>
          </el-descriptions>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="detailDialogVisible = false">关闭</el-button>
            </span>
          </template>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getLoginLogs } from '@/api/system/loginlog';
import { getOperationLogs } from '@/api/system/operationlog';

// 标签页激活状态
const activeTab = ref('login');

// 登录日志相关数据
const loginLogs = ref([]);
const loginLoading = ref(false);
const loginCurrentPage = ref(1);
const loginPageSize = ref(10);
const loginTotal = ref(0);
const loginSearchForm = ref({
  username: '',
  ip_address: '',
  status: '',
  date_range: []
});

// 操作日志相关数据
const operationLogs = ref([]);
const operationLoading = ref(false);
const operationCurrentPage = ref(1);
const operationPageSize = ref(10);
const operationTotal = ref(0);
const operationSearchForm = ref({
  username: '',
  request_method: '',
  status: '',
  date_range: []
});

// 详情对话框相关数据
const detailDialogVisible = ref(false);
const currentLog = ref({});

// 获取登录日志数据
async function fetchLoginLogs() {
  try {
    loginLoading.value = true;
    const params = {
      page: Number(loginCurrentPage.value),
      page_size: Number(loginPageSize.value),
      ...loginSearchForm.value,
      start_date: loginSearchForm.value.date_range[0],
      end_date: loginSearchForm.value.date_range[1]
    };
    const response = await getLoginLogs(params);
    loginLogs.value = response.data.results;
    loginTotal.value = response.data.count;
  } catch (error) {
    console.error('获取登录日志失败:', error);
  } finally {
    loginLoading.value = false;
  }
}

// 获取操作日志数据
async function fetchOperationLogs() {
  try {
    operationLoading.value = true;
    const params = {
      page: Number(operationCurrentPage.value),
      page_size: Number(operationPageSize.value),
      ...operationSearchForm.value,
      start_date: operationSearchForm.value.date_range[0],
      end_date: operationSearchForm.value.date_range[1]
    };
    const response = await getOperationLogs(params);
    operationLogs.value = response.data.results;
    operationTotal.value = response.data.count;
  } catch (error) {
    console.error('获取操作日志失败:', error);
  } finally {
    operationLoading.value = false;
  }
}

// 搜索和重置函数
function searchLoginLogs() {
  loginCurrentPage.value = 1;
  fetchLoginLogs();
}

function resetLoginSearch() {
  loginSearchForm.value = {
    username: '',
    ip_address: '',
    status: '',
    date_range: []
  };
  searchLoginLogs();
}

function searchOperationLogs() {
  operationCurrentPage.value = 1;
  fetchOperationLogs();
}

function resetOperationSearch() {
  operationSearchForm.value = {
    username: '',
    request_method: '',
    status: '',
    date_range: []
  };
  searchOperationLogs();
}

// 分页处理函数
function handleLoginSizeChange(val) {
  loginPageSize.value = val;
  fetchLoginLogs();
}

function handleLoginCurrentChange(val) {
  loginCurrentPage.value = val;
  fetchLoginLogs();
}

function handleOperationSizeChange(val) {
  operationPageSize.value = val;
  fetchOperationLogs();
}

function handleOperationCurrentChange(val) {
  operationCurrentPage.value = val;
  fetchOperationLogs();
}

// 请求方法标签类型
function getMethodTagType(method) {
  const typeMap = {
    GET: 'info',
    POST: 'success',
    PUT: 'warning',
    DELETE: 'danger'
  };
  return typeMap[method] || 'info';
}

// 状态码标签类型
function getStatusTagType(status) {
  if (status >= 200 && status < 300) return 'success';
  if (status >= 300 && status < 400) return 'info';
  if (status >= 400 && status < 500) return 'warning';
  return 'danger';
}

// 显示详情
function showDetail(row) {
  currentLog.value = row;
  detailDialogVisible.value = true;
}

// 组件挂载时加载数据
onMounted(() => {
  fetchLoginLogs();
  fetchOperationLogs();
});
</script>

<style scoped>
.system-log {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-tag {
  margin-right: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>